package cn.iocoder.yudao.module.member.dal.mysql.user;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.MPJLambdaWrapperX;
import cn.iocoder.yudao.module.member.controller.admin.user.vo.MemberUserPageReqVO;
import cn.iocoder.yudao.module.member.controller.app.user.vo.AppMemberUserInfoPageReqVO;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Mapper;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 会员 User Mapper
 *
 * @author 尔加源码
 */
@Mapper
public interface MemberUserMapper extends BaseMapperX<MemberUserDO> {

    default MemberUserDO selectByMobile(String mobile) {
        return selectOne(MemberUserDO::getMobile, mobile);
    }

    default List<MemberUserDO> selectListByNicknameLike(String nickname) {
        return selectList(new LambdaQueryWrapperX<MemberUserDO>()
                .likeIfPresent(MemberUserDO::getNickname, nickname));
    }

    default PageResult<MemberUserDO> selectPage(MemberUserPageReqVO reqVO) {
        // 处理 tagIds 过滤条件
        String tagIdSql = "";
        if (CollUtil.isNotEmpty(reqVO.getTagIds())) {
            tagIdSql = reqVO.getTagIds().stream()
                    .map(tagId -> "FIND_IN_SET(" + tagId + ", tag_ids)")
                    .collect(Collectors.joining(" OR "));
        }
        // 分页查询
        return selectPage(reqVO, new LambdaQueryWrapperX<MemberUserDO>()
                .eqIfPresent(MemberUserDO::getId, reqVO.getId())
                .likeIfPresent(MemberUserDO::getMobile, reqVO.getMobile())
                .betweenIfPresent(MemberUserDO::getLoginDate, reqVO.getLoginDate())
                .likeIfPresent(MemberUserDO::getNickname, reqVO.getNickname())
                .eqIfPresent(MemberUserDO::getSex, reqVO.getSex())
                .betweenIfPresent(MemberUserDO::getCreateTime, reqVO.getCreateTime())
                .eqIfPresent(MemberUserDO::getLevelId, reqVO.getLevelId())
                .eqIfPresent(MemberUserDO::getGroupId, reqVO.getGroupId())
                .apply(StrUtil.isNotEmpty(tagIdSql), tagIdSql)
                .orderByDesc(MemberUserDO::getId));
    }

    default PageResult<MemberUserDO> selectPage(AppMemberUserInfoPageReqVO reqVO) {
        if(StringUtils.isNotBlank(reqVO.getKeyword())){
            return selectJoinPage(reqVO, MemberUserDO.class, new MPJLambdaWrapperX<MemberUserDO>()
                    .leftJoin(reqVO.getUserId() != null, "im_member_conversation imc ON t.id = imc.user_id AND imc.by_user_id = "+reqVO.getUserId())
                    .eq(MemberUserDO::getStatus, CommonStatusEnum.ENABLE.getStatus())
                    .eq(MemberUserDO::getSex, reqVO.getSex())
                    .eq(StringUtils.isNotBlank(reqVO.getCity()), MemberUserDO::getCity, reqVO.getCity())
                    .isNull(reqVO.getUserId() != null,"imc.by_user_id")
                    .and((e)->{
                        e.or().like(MemberUserDO::getNickname, reqVO.getKeyword());
                        e.or().like(MemberUserDO::getAge, reqVO.getKeyword());
                        e.or().like(MemberUserDO::getCity, reqVO.getKeyword());
                    })
                    .orderByDesc(MemberUserDO::getVisitNum,MemberUserDO::getUpdateTime));
        }
        // 分页查询
        return selectJoinPage(reqVO, MemberUserDO.class, new MPJLambdaWrapperX<MemberUserDO>()
                .leftJoin(reqVO.getUserId() != null, "im_member_conversation imc ON t.id = imc.user_id AND imc.by_user_id = "+reqVO.getUserId())
                .eq(MemberUserDO::getStatus, CommonStatusEnum.ENABLE.getStatus())
                .eq(MemberUserDO::getSex, reqVO.getSex())
                .between(MemberUserDO::getAge, reqVO.getMinAge(), reqVO.getMaxAge())
                .eq(StringUtils.isNotBlank(reqVO.getCity()), MemberUserDO::getCity, reqVO.getCity())
                .isNull(reqVO.getUserId() != null,"imc.by_user_id")
                .orderByDesc(MemberUserDO::getVisitNum,MemberUserDO::getUpdateTime));
    }

    default Long selectCountByGroupId(Long groupId) {
        return selectCount(MemberUserDO::getGroupId, groupId);
    }

    default Long selectCountByLevelId(Long levelId) {
        return selectCount(MemberUserDO::getLevelId, levelId);
    }

    default Long selectCountByTagId(Long tagId) {
        return selectCount(new LambdaQueryWrapperX<MemberUserDO>()
                .apply("FIND_IN_SET({0}, tag_ids)", tagId));
    }

    /**
     * 更新用户积分（增加）
     *
     * @param id        用户编号
     * @param incrCount 增加积分（正数）
     */
    default void updatePointIncr(Long id, Integer incrCount) {
        Assert.isTrue(incrCount > 0);
        LambdaUpdateWrapper<MemberUserDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<MemberUserDO>()
                .setSql(" point = point + " + incrCount)
                .eq(MemberUserDO::getId, id);
        update(null, lambdaUpdateWrapper);
    }

    /**
     * 更新用户积分（减少）
     *
     * @param id        用户编号
     * @param incrCount 增加积分（负数）
     * @return 更新行数
     */
    default int updatePointDecr(Long id, Integer incrCount) {
        Assert.isTrue(incrCount < 0);
        LambdaUpdateWrapper<MemberUserDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<MemberUserDO>()
                .setSql(" point = point + " + incrCount) // 负数，所以使用 + 号
                .eq(MemberUserDO::getId, id);
        return update(null, lambdaUpdateWrapper);
    }

    default List<MemberUserDO> getWeekTopList(Integer sex){
        return selectList(new LambdaQueryWrapperX<MemberUserDO>()
                .select(MemberUserDO::getId,MemberUserDO::getAvatar,MemberUserDO::getNickname,MemberUserDO::getPoint)
                .eq(MemberUserDO::getSex, sex)
                .eq(MemberUserDO::getStatus, CommonStatusEnum.ENABLE.getStatus())
                .gt(MemberUserDO::getExperience, 0)
                .eq(MemberUserDO::getVisible, true)
                .orderByDesc(MemberUserDO::getExperience, MemberUserDO::getId).last("LIMIT 3"));
    };

    default List<MemberUserDO> getMemberNewList(){
        return selectList(new LambdaQueryWrapperX<MemberUserDO>()
                .select(MemberUserDO::getId,MemberUserDO::getAvatar,MemberUserDO::getNickname,MemberUserDO::getPoint)
                .eq(MemberUserDO::getStatus, CommonStatusEnum.ENABLE.getStatus())
                //.eq(MemberUserDO::getIsWelcome, CommonStatusEnum.ENABLE.getStatus())
                .eq(MemberUserDO::getVisible, true)
                .orderByDesc(MemberUserDO::getId).last("LIMIT 20"));
    }

    default List<MemberUserDO> getMemberHotList(){
        return selectList(new LambdaQueryWrapperX<MemberUserDO>()
                .select(MemberUserDO::getId,MemberUserDO::getAvatar,MemberUserDO::getNickname,MemberUserDO::getPoint,MemberUserDO::getSlashedTime)
                .eq(MemberUserDO::getStatus, CommonStatusEnum.ENABLE.getStatus())
                .eq(MemberUserDO::getVisible, true)
                .gt(MemberUserDO::getSlashedTime, DateUtil.toLocalDateTime(DateUtil.date()))
                .orderByDesc(MemberUserDO::getSlashedTime, MemberUserDO::getUpdateTime).last("LIMIT 20"));
    }

    default MemberUserDO getRandomUser(Long userId){
        MemberUserDO member = selectById(userId);
        int sex = 2;
        if(member.getSex().intValue() == 1){
            sex = 2;
        }else if(member.getSex().intValue() == 2){
            sex = 1;
        }

        DateTime now = DateUtil.offsetDay(DateUtil.date(), -30);
        return selectJoinOne(MemberUserDO.class, new MPJLambdaWrapperX<MemberUserDO>()
                .leftJoin("im_member_conversation imc ON t.id = imc.user_id AND imc.by_user_id = "+userId)
                .leftJoin("system_social_user_bind sub ON t.id = sub.user_id")
                .leftJoin("system_social_user su ON su.id = sub.social_user_id")
                .leftJoin("mp_user mpu ON su.union_id = mpu.union_id")
                .eq(MemberUserDO::getStatus, CommonStatusEnum.ENABLE.getStatus())
                .eq(MemberUserDO::getVisible, true)
                .eq(MemberUserDO::getSex, sex)
                .gt(MemberUserDO::getUpdateTime, DateUtil.toLocalDateTime(now))
                .gt(MemberUserDO::getMatchCount, 0)
                .eq("mpu.subscribe_status", CommonStatusEnum.ENABLE.getStatus())
                .isNull("imc.by_user_id")
                .orderByDesc(MemberUserDO::getMatchCount,MemberUserDO::getMatchTime).last("LIMIT 1"));
    }

    default void updateUserMatchNum(Long id, Integer matchNum, Integer matchCount, LocalDateTime matchTime){
        LambdaUpdateWrapper<MemberUserDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<MemberUserDO>()
                .set(MemberUserDO::getMatchNum, matchNum)
                .set(MemberUserDO::getMatchCount, matchCount)
                .set(MemberUserDO::getMatchTime, matchTime)
                .eq(MemberUserDO::getId, id);
        update(null, lambdaUpdateWrapper);
    }

    default List<MemberUserDO> getMemberList(){
        return selectList(new LambdaQueryWrapperX<MemberUserDO>()
                .select(MemberUserDO::getId)
                .eq(MemberUserDO::getStatus, CommonStatusEnum.ENABLE.getStatus())
                //.eq(MemberUserDO::getSex, 2)
                .eq(MemberUserDO::getVisible, true));
    }

    default MemberUserDO getRandomMember(Long userId){
        MemberUserDO member = selectById(userId);
        int sex = 2;
        if(member.getSex().intValue() == 1){
            sex = 2;
        }else if(member.getSex().intValue() == 2){
            sex = 1;
        }

        DateTime now = DateUtil.offsetDay(DateUtil.date(), -30);
        return selectJoinOne(MemberUserDO.class, new MPJLambdaWrapperX<MemberUserDO>()
                .leftJoin("im_member_conversation imc ON t.id = imc.user_id AND imc.by_user_id = "+userId)
                .leftJoin("system_social_user_bind sub ON t.id = sub.user_id")
                .leftJoin("system_social_user su ON su.id = sub.social_user_id")
                .leftJoin("mp_user mpu ON su.union_id = mpu.union_id")
                .eq(MemberUserDO::getStatus, CommonStatusEnum.ENABLE.getStatus())
                .eq(MemberUserDO::getVisible, true)
                .eq(MemberUserDO::getSex, sex)
                .gt(MemberUserDO::getUpdateTime, DateUtil.toLocalDateTime(now))
                .eq("mpu.subscribe_status", CommonStatusEnum.ENABLE.getStatus())
                .isNull("imc.by_user_id")
                .orderByDesc(MemberUserDO::getMatchTime).last("LIMIT 1"));
    }
}
